package com.wmh.baseservice.common.mybatisplus.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;

/**
 * @author 谢骏
 * @date 2023/9/10 14:41
 * Set<Long> 字段 操作数据库时 json 序列化 与 反序列化
 **/
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Set.class)
@Slf4j
public class JsonLongSetTypeHandler implements TypeHandler<Set<Long>>{

    private static final TypeReference<Set<Long>> TYPE_REFERENCE = new TypeReference<Set<Long>>(){};
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Set<Long> longs, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSON.toJSONString(longs));
    }

    @Override
    public Set<Long> getResult(ResultSet resultSet, String s) throws SQLException {
        return JSON.parseObject(resultSet.getString(s),TYPE_REFERENCE);
    }

    @Override
    public Set<Long> getResult(ResultSet resultSet, int i) throws SQLException {
        return JSON.parseObject(resultSet.getString(i),TYPE_REFERENCE);
    }

    @Override
    public Set<Long> getResult(CallableStatement callableStatement, int i) throws SQLException {
        return JSON.parseObject(callableStatement.getString(i),TYPE_REFERENCE);
    }
}
